#!/usr/bin/python

import sys
import os
from os import walk
from os import path

def exportFile(inputFile, outputFile):
    
    inputFile.readline()
    name = inputFile.readline().strip()
    inputFile.readline()
    inputFile.readline()
    
    nCols = inputFile.readline().split("=")[1].strip()
    nRows = inputFile.readline().split("=")[1].strip()
    east = inputFile.readline().strip()+'0'
    north = inputFile.readline().strip()+'0'
    avg = inputFile.readline().strip()
    
    outputFile.write('\t<sector name="'+name+'" nRows="'+nRows+'" nCols="'+nCols+'" east="'+east+'" north="'+north+'" avg="'+avg+'"/>\n')
    

def parseFile(inputFilename, outputFile):
    try:
        inputFile = open(inputFilename,'r')
        exportFile(inputFile, outputFile)
        inputFile.close()
    except IOError:
        print "There was an error writing to", file_name
        sys.exit()

def doIt(inputDir, outputDir, mapName):
    print(inputDir);
    print(outputDir);
    
    if not os.path.exists(outputDir):
        os.makedirs(outputDir)

    outputFilename = outputDir+'/'+mapName+'.xml'
    outputFile = open(outputFilename,'w+')
    
    outputFile.write('<map name="'+mapName+'">\n');
    
    f = [];
    for (dirpath, dirnames, filenames) in walk(inputDir):
        f.extend(filenames);
        for filename in f:
            (name, ext) = path.splitext(filename)
            if(ext == ".DEM"):
                inputFilename = inputDir + '/' + filename
                parseFile(inputFilename,outputFile)
        break;
    
    outputFile.write('</map>\n');
    outputFile.close()

# usage: dem_parser inputdir outputdir mapname

if sys.argv > 0:
    inputDir = str(sys.argv[1]);
    outputDir = str(sys.argv[2]);
    mapName = str(sys.argv[3]);
    doIt(inputDir,outputDir,mapName);